import { getCurrentInstance } from 'vue';
import {ImageNode} from "@/canvasCut/package/node";

export function chooseImg() {
    return new Promise((resolve, reject) => {
        uni.chooseMedia({
            count: 1,
            mediaType: ['image'],
            success: function(res){
                uni.getImageInfo({
                    src: res.tempFiles[0].tempFilePath,
                    success: function (image) {
                        resolve({
                            imageData: res.tempFiles[0].tempFilePath,
                            width: image.width,
                            height: image.height,
                            type: 'image',
                            _detail: image
                        })
                    },
                    fail: function(err){
                        reject(err)
                    }
                });
            },
            fail: function(err){
                reject(err)
            }
        })
    })
}


/**
 * 下载网络图片
 * @param src
 */
export function downImg(src: string) {
    return new Promise((resolve, reject) => {
        uni.getImageInfo({
            src: src,
            success: function (image) {
                resolve({
                    imageData: image.path,
                    width: image.width,
                    height: image.height,
                    type: 'image',
                    _detail: image
                })
            },
            fail: function(err){
                uni.hideLoading()
                console.log(err);
                uni.showToast("下载图片失败")
            }
        });


    })
}


/**
 * 获取节点信息
 * @param query
 */
export function selectQuery(query: string) {
    return new Promise((resolve, reject) => {
        uni.createSelectorQuery().select(query).boundingClientRect(function(res) {
            resolve(res)
        }).exec();
    })
}


/**
 * 获取Canvas节点信息
 * @param query
 */
export function selectCanvasQuery(canvasId: string) {
    return new Promise((resolve, reject) => {
        uni.createSelectorQuery().select(canvasId)
            .fields({ node: true, size: true })
            .exec((res) => {
                console.log('re-------s', res)
                const canvas = res[0].node
                const ctx = canvas.getContext('2d');
                // Canvas 画布的实际绘制宽高
                const renderWidth = res[0].width
                const renderHeight = res[0].height
                // Canvas 绘制上下文

                // 初始化画布大小
                const dpr = wx.getWindowInfo().pixelRatio
                canvas.width = renderWidth * dpr
                canvas.height = renderHeight * dpr
                ctx.scale(dpr, dpr)

                setTimeout(() => {
                    resolve({
                        canvas,
                        ctx
                    })
                },1500)
            });

    })
}

/**
 * 图片位置 大小 计算
 * @param width 图片宽度
 * @param height 图片高度
 * @param contentWidth 容器宽度
 * @param contentHeight 容器高度
 * @param maxWidth 最大宽度
 * @param maxHeight 最大高度
 */
export function calculateImagePosition(width, height, contentWidth, contentHeight, maxWidth, maxHeight) {
    // console.log('calculateImagePosition', width, height, contentWidth, contentHeight, maxWidth, maxHeight)
    // 处理最大宽高限制为null/undefined的情况
    const actualMaxWidth = maxWidth !== undefined && maxWidth !== null ? Math.min(contentWidth, maxWidth) : contentWidth;
    const actualMaxHeight = maxHeight !== undefined && maxHeight !== null ? Math.min(contentHeight, maxHeight) : contentHeight;

    // 如果原始图片宽高均小于实际最大宽高，直接居中放置
    if (width <= actualMaxWidth && height <= actualMaxHeight) {
        return {
            x: (contentWidth - width) / 2,
            y: (contentHeight - height) / 2,
            w: width,
            h: height,
            scale: 1
        };
    }

    // 计算缩放比例（保持宽高比）
    const widthRatio = actualMaxWidth / width;
    const heightRatio = actualMaxHeight / height;
    const scale = Math.max(widthRatio, heightRatio);

    // 计算缩放后的尺寸
    const scaledWidth = width * scale;
    const scaledHeight = height * scale;

    // 计算居中位置
    const x = (contentWidth - scaledWidth) / 2;
    const y = (contentHeight - scaledHeight) / 2;

    return {
        x: x,
        y: y,
        w: scaledWidth,
        h: scaledHeight,
        scale: scale
    };
}
//
// // 测试用例
// console.log("测试1: 原始图片小于容器和最大限制");
// console.log(calculateImagePosition(200, 150, 400, 300, 500, 400));
// // 输出: {x: 100, y: 75, w: 200, h: 150}
//
// console.log("\n测试2: 原始图片大于容器但小于最大限制");
// console.log(calculateImagePosition(800, 600, 400, 300, 1000, 800));
// // 输出: {x: 0, y: 0, w: 400, h: 300}
//
// console.log("\n测试3: 原始图片大于最大限制");
// console.log(calculateImagePosition(1200, 800, 600, 400, 500, 400));
// // 输出: {x: 50, y: 0, w: 500, h: 333.33...}
//
// console.log("\n测试4: 超高图片，最大高度限制");
// console.log(calculateImagePosition(300, 500, 400, 300, 600, 200));
// // 输出: {x: 133.33..., y: 0, w: 200, h: 333.33...}
//
// console.log("\n测试5: 无最大限制");
// console.log(calculateImagePosition(1200, 800, 600, 400, null, null));
// // 输出: {x: 0, y: 50, w: 600, h: 400}
//
// console.log("\n测试6: 只有最大宽度限制");
// console.log(calculateImagePosition(1200, 800, 600, 400, 500, null));
// // 输出: {x: 50, y: 33.33..., w: 500, h: 333.33...}

// 核心方法：保持宽高比绘制
export function drawImageWithAspectRatio(img, canvasWidth, canvasHeight) {
    // 1. 计算缩放比例
    const scale = Math.min(
        canvasWidth / img.width,
        canvasHeight / img.height
    );

    console.log('scale', scale)

    // 2. 计算绘制尺寸
    const drawWidth = img.width * scale;
    const drawHeight = img.height * scale;

    // 3. 计算居中位置
    const x = (canvasWidth - drawWidth) / 2;
    const y = (canvasHeight - drawHeight) / 2;

    return {
        img,
        x: parseInt(x, 0),
        y: parseInt(y, 0),
        w: parseInt(drawWidth, 0),
        h: parseInt(drawHeight, 0),
        scale
    }
}

/**
 * 创建图片节点
 * @param canvas
 * @param imgSrc
 */
export function createImageNode(canvas, imgSrc) {
    return new Promise((resolve, reject) => {
        const image = canvas.createImage()
        image.onload = (res) => {

            resolve( {image})
        }
        image.src = imgSrc
    })
}
